const path = require('path');
const {
	HotModuleReplacementPlugin,
	IgnorePlugin
} = require('webpack');
const webpack = require('webpack');
const {
	CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {
	VueLoaderPlugin
} = require('vue-loader');
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const tsImportPluginFactory = require('ts-import-plugin')
function resolve(dir) {
    return path.resolve(__dirname, dir);
}

const config = {
	mode: 'development',
	//定义页面的入口, 因为js中将要使用es6语法, 所以这里需要依赖 babel 垫片
	entry: {
		index: ['@babel/polyfill', './src/main.ts'],
		about: ['@babel/polyfill', './src/about.ts']
	},
	output: {
    publicPath: '',
		// path: resolve('dist'), // 指示发布目录
		filename: 'js/[name].[chunkhash:8].js' //指示生成的页面入口js文件的目录和文件名, 中间包含8位的hash值
	},
	devServer: {
		contentBase: false,
		// contentBase: './dist',
		hot: true,
		port: 8080,
		open: true,
		// hotOnly: true,
		compress: true,
		overlay: true
	},
	watchOptions: {
		ignored: /node_modules/
	},
	plugins: [
		//引入全局变量
		new webpack.ProvidePlugin({
			$: 'jquery',
			jQuery: 'jquery',
			"window.jQuery": 'jquery',
			"window.$": 'jquery'
		}),
		new CleanWebpackPlugin(),
		new HtmlWebpackPlugin({
			title: 'vue3 + TS -> web App',
			minify: {
				removeComments: true,// 去掉注释
				collapseWhitespace: true,// 去掉空格
				collapseBooleanAttributes: true,
				removeScriptTypeAttributes: true,
			},
			template: './public/index.html',
			filename: 'index.html',
			inject: true,
			prod: false,
		}),
		new MiniCssExtractPlugin({
			filename: '[name].css',
			chunkFilename: '[id].css',
		}),
		new IgnorePlugin(/^\.\/locale$/, /moment$/),
		// new HotModuleReplacementPlugin(),
		new VueLoaderPlugin(),
		//new FriendlyErrorsWebpackPlugin(),
	],
	resolve: {
		extensions: [
			'.tsx','.ts','.js','.jsx','.vue','.json'],
		alias: {
			// vue$: 'vue/dist/vue.esm-bundler.js',
			'src': resolve('src'),
			'assets': resolve('src/assets'),
			'components': resolve('src/components'),
			'router': resolve('src/router')
		},
	},
	module: {
		rules: [
			// babel使用runtime，避免将不需要的代码注入
			{
				test: /\.js$/,
				exclude: /node_modules/,
				include: path.resolve(__dirname, 'src'),
				use: [{
					loader: 'babel-loader',
					options: {
						// cacheDirectory: true,
						presets: ['@babel/preset-env'],
						plugins: [
							'@babel/plugin-transform-runtime',
							['import', {
								"libraryName": "antd",
								"style": true, // or 'css'
							}, 'antd']
						]
					}
				}],
			},
			{
				test: /\.ts$/,
				exclude: /node_modules/,
				use: [{
					loader: 'ts-loader',
					options: {
						// 指定特定的ts编译配置，为了区分脚本的ts配置
						transpileOnly: true,
						getCustomTransformers: () => ({
							before: [
							  tsImportPluginFactory({
								libraryName: 'vant',
								libraryDirectory: 'es',
								style: (name) => `${name}/style/less`,
							  }),
							],
						  }),
						  compilerOptions: {
							module: 'es2015',
						  },
						configFile: path.resolve(__dirname, './tsconfig.json'),
						appendTsSuffixTo: [/\.vue$/]
					}
				}]
			},
			{
				test: /\.vue$/,
				loader: 'vue-loader'
			},
			{
				test: /\.css$/,
				use: [{
						loader: MiniCssExtractPlugin.loader,
						options: {},
					},
					{
						loader: 'css-loader',
						options: {
							sourceMap: false,
							importLoaders: 2
						},
					},
					{
						loader: 'postcss-loader',
					},
				],
			},
			{
				test: /\.less$/,
				use: ['style-loader', 'css-loader',
					{
						loader: 'less-loader',
						options: {
							lessOptions: {
								modifyVars: {
									'primary-color': '#4608e2',
									'link-color': '#4608e2',
									'border-radius-base': '20px',
								},
								javascriptEnabled: true,
							}
						}
					}
				],
			},{
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
        use: 'url-loader?limit=10000&name=fonts/[name].[hash:8].[ext]',
      }, {
        test: /\.(swf|mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        use: 'url-loader?limit=10000&name=media/[name].[hash:8].[ext]',
      },  {
				test: /\.(gif|png|jpe?g|svg|ico)$/i,
				use: [{
					loader: 'url-loader',
					options: {
						// name: 'assets/[name].[hash:5].[ext]',
						limit: 200, // 小于8k的图片自动转成base64格式，并且不会存在实体图片,
						// publicPath:'./'
						fallback: {
							loader: 'file-loader',
							options: {
								name: 'assets/[name].[ext]'
							}
						}
					},
				}, ],
			},
		]
	},
};

module.exports = (env) => {
	console.log(`当前执行${env.mode}模式`);
	return config;
}
